package com.zy.interceptor;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 创建一个拦截器并实现HandlerInterceptor
 * @author 张宇
 * @date 2021/7/27 17:09
 */
@Component
public class LoginInterceptor implements HandlerInterceptor
{

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        String token = request.getHeader("Authorization");//获取Header中的参数
        token = (token == null) ? "" : token;
        Long expire = redisTemplate.getExpire(token);//查询token在redis中的剩余时间
        if(expire > 0)
        {
            redisTemplate.expire(token,12L, TimeUnit.HOURS);
            return true;
        }
        else
        {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String,Object> map = new HashMap<>();
            map.put("code",401);
            map.put("msg","请求访问：{" + request.getRequestURI() + "}" + "认证失败，无法访问系统资源");
            String string = JSON.toJSONString(map);
            response.getWriter().print(string);
            return false;
        }
    }

}
